package com.example.finalproject.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.finalproject.R;
import com.example.finalproject.bean.WeatherBean;
import com.example.finalproject.utils.NetUtil;
import com.google.gson.Gson;

public class WeatherFragment extends Fragment {
    private AppCompatSpinner spinnerCity;
    private ArrayAdapter<String> spinnerAdapter;
    private String[] cities;
    private String selectedCity;
    private ViewGroup rootLayout;
    private ImageView imageWeather, wallpaperView;
    private TextView textCity, textDateWeek, textTempNow, textTempRange, textHumidity, textWeatherDesc, textWind, textAQI;

    public WeatherFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_weather, container, false);

        spinnerCity = root.findViewById(R.id.spinnerCity);
        textCity = root.findViewById(R.id.textCity);
        textDateWeek = root.findViewById(R.id.textDateWeek);
        textTempNow = root.findViewById(R.id.textTempNow);
        textTempRange = root.findViewById(R.id.textTempRange);
        imageWeather = root.findViewById(R.id.imageWeather);
        textWeatherDesc = root.findViewById(R.id.textWeatherDesc);
        textHumidity = root.findViewById(R.id.textHumidity);
        textWind = root.findViewById(R.id.textWind);
        textAQI = root.findViewById(R.id.textAQI);
        rootLayout = root.findViewById(R.id.weatherRootLayout);
        wallpaperView = root.findViewById(R.id.wallpaperView);

        setupCitySpinner();
        applyWallpaper();  // 设置背景壁纸
        return root;
    }

    public void onResume() {
        super.onResume();
        applyWallpaper();  // 每次进入页面时更新壁纸背景
    }

    /** 绑定 Spinner 和城市下拉列表 */
    private void setupCitySpinner() {
        cities = getResources().getStringArray(R.array.city_list);
        spinnerAdapter = new ArrayAdapter<String>(
                requireContext(),
                android.R.layout.simple_spinner_item,
                cities
        );
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCity.setAdapter(spinnerAdapter);
        spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                selectedCity = parent.getItemAtPosition(pos).toString();
//                fetchWeatherData(selectedCity);
                spinnerCity.postDelayed(() -> {
                    fetchWeatherData(selectedCity);
                }, 300);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 不选时可留空
            }
        });
    }

    private void fetchWeatherData(String city) {
        new Thread(() -> {
            String weatherOfCity = NetUtil.getWeatherOfCity(city, requireContext());
            Message message = Message.obtain();
            message.what = 0;
            message.obj = weatherOfCity;
            handler.sendMessage(message);
        }).start();
    }

    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String weather = (String) msg.obj;
                Log.d("result", "--主线程接收到了天气数据--" + weather);
                if (weather.isEmpty()) {
                    Log.d("result", "天气数据为空!" + weather);
                    return;
                }

                Gson gson = new Gson();
                WeatherBean weatherBean = gson.fromJson(weather, WeatherBean.class);
                if (weatherBean != null) {
                    Log.d("result", "--解析后的天气数据--" + weatherBean);
                    updateUiOfWeather(weatherBean);
                }
            }
        }
    };

    private void updateUiOfWeather(WeatherBean weatherBean) {
        if (weatherBean == null) {
            return;
        }

        textCity.setText(weatherBean.getCity());
        textAQI.setText("空气质量(AQI): " + weatherBean.getAir());
        textHumidity.setText("湿度：" + weatherBean.getHumidity());
        textTempNow.setText(weatherBean.getTem() + "℃");
        textDateWeek.setText(weatherBean.getDate() + weatherBean.getWeek());
        textTempRange.setText(weatherBean.getTem_night() + " - " + weatherBean.getTem_day() + "℃");
        textWind.setText("风：" + weatherBean.getWin_speed() + " " + weatherBean.getWin());
        textWeatherDesc.setText(weatherBean.getWea());
        imageWeather.setImageResource(getImgResOfWeather(weatherBean.getWea_img()));
    }

    private int getImgResOfWeather(String weaImg) {
        switch (weaImg) {
            case "xue":
                return R.drawable.icon_xue;
            case "lei":
                return R.drawable.icon_lei;
            case "shachen":
                return R.drawable.icon_shachen;
            case "wu":
                return R.drawable.icon_wu;
            case "bingbao":
                return R.drawable.icon_bingbao;
            case "yun":
                return R.drawable.icon_yun;
            case "yu":
                return R.drawable.icon_yu;
            case "yin":
                return R.drawable.icon_yin;
            case "qing":
                return R.drawable.icon_qing;
            default:
                return R.drawable.weather; // 默认图标，用于防止空指针或未知值
        }
    }

    public void applyWallpaper() {
        SharedPreferences prefs = requireContext().getSharedPreferences("weatherPrefs", Context.MODE_PRIVATE);
        String name = prefs.getString("wallpaperName", "wallpaper_forest"); // 默认为wallpaper
        int resId = getResources().getIdentifier(name, "drawable", requireContext().getPackageName());
        wallpaperView.setImageResource(resId);
    }
}